import React, { useEffect, useState } from 'react'
import style from './calendar.module.css'
import { Calendar, ConfigProvider } from 'antd';
import type { Dayjs } from 'dayjs';
import zhCN from 'antd/es/locale/zh_CN'; // 引入 Ant Design 的中文包
import dayjs from 'dayjs';

import 'dayjs/locale/zh-cn';

dayjs.locale('zh-cn');
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
// 56个节假日
const holidayTranslations = {
  "New Year's Day": "元旦",
  "Special Working Day": "特别工作日",
  "Spring Festival Eve": "除夕",
  "Chinese New Year": "春节",
  "Spring Festival Golden Week holiday": "春节黄金周假期",
  "Lantern Festival": "元宵节",
  "International Women's Day": "国际妇女节",
  "Zhonghe Festival": "中和节",
  "Arbor Day": "植树节",
  "March Equinox": "春分",
  "Qing Ming Jie": "清明节",
  "Qing Ming Jie holiday": "清明节假期",
  "Labour Day": "劳动节",
  "Labour Day Holiday": "劳动节假期",
  "Youth Day": "青年节",
  "Children's Day": "儿童节",
  "Dragon Boat Festival": "端午节",
  "June Solstice": "夏至",
  "CPC Founding Day": "中国共产党成立纪念日",
  "Maritime Day": "海洋日",
  "Army Day": "建军节",
  "Chinese Valentine's Day": "七夕节",
  "Spirit Festival": "中元节",
  "Teachers' Day": "教师节",
  "Mid-Autumn Festival holiday": "中秋节假期",
  "Mid-Autumn Festival": "中秋节",
  "September Equinox": "秋分",
  "National Day": "国庆节",
  "National Day Golden Week Holiday": "国庆黄金周假期",
  "Double Ninth Festival": "重阳节",
  "Journalists' Day": "记者节",
  "December Solstice": "冬至",
  "Christmas Day": "圣诞节",
  "National Day Golden Week holiday":"国庆假期"
};
const CalendarData = () => {
  const [holidays, setHolidays] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    // 获取节假日数据
    const fetchHolidays = async () => {
      try {
        // TLMiDFmueHqNAufpOTU6g0R3aKz3PedC
        // const response = await axios.get(`https://calendarific.com/api/v2/holidays?&api_key=TLMiDFmueHqNAufpOTU6g0R3aKz3PedC&country=CN&year=2024&language=zh`);
        const response = await axios.get(`https://calendarific.com/api/v2/holidays?&api_key=TLMiD60R3aKz3PedC&country=CN&year=2024&language=zh`);
        // 2024年节假日
        console.log(response.data.response.holidays)
        const holidayData = response.data.response.holidays.reduce((acc, holiday) => {
          const holidayName = holidayTranslations[holiday.name] || holiday.name; // 使用映射
          acc[holiday.date.iso] = holidayName;
          return acc;
        }, {});
        setHolidays(holidayData);
      } catch (error) {
        console.error('节日错误:', error);
      }
    };

    fetchHolidays();
  }, []);

  const getListData = (value: Dayjs) => {
    let listData: { type: string; content: string }[] = [];
    const dateStr = value.format('YYYY-MM-DD');// 将日期格式化为字符串
    // 检查是否为节假日
    if (holidays[dateStr]) {
      listData.push({ type: 'success', content: holidays[dateStr] });// 如果是节假日，加入列表
    }
    return listData;
  };
  const navigate = useNavigate()
  const toGo = (item) => {
    const formConent = encodeURIComponent(item.content);// 对内容进行编码
    navigate(`/home/createteam?content=${formConent}`)// 导航到指定页面
  }
  // 用于自定义渲染日历中的每一天 
  const dateCellRender = (value: Dayjs) => {
    // 调用getListData函数，传入当前日期value，获取该日期的节日数据列表
    const listData = getListData(value);
    // 初始化一个字符串，用于存储月份第一天的文本  
    let monthFirstDayText = ''
    if (value.date().toString() === '1') {//检查是否是月份的第一天
      // 如果是月份的第一天，则根据当前日期格式化出月份名称，并附加“你好”字样  
      monthFirstDayText = `${value.format('MMMM')}你好`
    }
    // 点击函数
    const handleClick = (event: React.MouseEvent<HTMLDivElement>, content: string) => {
      console.log('click', content)
    }
    return (
      <div style={{ width: '120px', height: '30px' }} onClick={(e) => handleClick(e, monthFirstDayText || (listData.length > 0 ? listData[0].content : ''))}>
        {/* 如果monthFirstDayText不为空（即当前是月份的第一天），则渲染月份第一天的文本 */
      /* 使用b标签高亮显示，并设置文字颜色为橙色 */}
        {monthFirstDayText && <div><b style={{ color: 'orange' }}>|</b>{monthFirstDayText}</div>}
        {listData.map((item) => (
          <li key={item.content} onClick={() => toGo(item)}>
            <span><b>|</b>{item.content}</span>
          </li>
        ))}
      </div>
    )
  }
  return (
    <div className={style.calendar}>
      <ConfigProvider locale={zhCN}>
        {/* 其他需要中文环境的组件也可以放在这里 */}
        <Calendar className={style.calent} cellRender={dateCellRender} />
      </ConfigProvider>

    </div>
  );
}

export default CalendarData;
